<?php

class Article extends Eloquent {

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'articles';
    const TYPE_INFO = 368;		// 资讯
    const TYPE_LAW = 369;		// 法规
    const TYPE_CASE = 370;		// 案例
    const TYPE_LIBRARY = 371;	// 文库
    const TYPE_DOCUMENT = 374;	// 文书下载
    const TYPE_SITEINFO = 375;  // 关于我们，网站信息

    const STATUS_APPROVED = 1;  // 审核通过
    const STATUS_PENDING = 0;   // 有待审核
    const STATUS_UNAPPROVED = -1; //审核未通过
    const STATUS_DRAFTS  = 2;  //草稿箱

    const VISIBILITY_ALL = 0; // 所有人
    const VISIBILITY_FOLLOWER = 1; // 关注我的人
    const VISIBILITY_PRIVATE = 2; // 私人文章


	/**
	 * Get the unique identifier for the user.
	 *
	 * @return mixed
	 */
	protected $primaryKey = 'id';
		
	/**
	 * 软删除
	 * @var boolean
	 */
	protected $softDelete = true;
	
	public function articleClass()
	{
		return $this->belongsTo('ArticleClass', 'article_class_id');
	}

	public function articleContent()
	{
		$article_info = ArticleInfo::find($this->id);
		if($article_info){
			return $article_info->content;
		}
		return;
	}
	
	public function getAuthor(){
		$Author = [];
		if($this->from_admin){
			$Author['author_avatar'] = UtilsHelper::getImage(null, 'img/succreturn-logo.png');
			$Author['author_id'] = 1;
			$Author['author_name'] = '律团';
		}else{
			$user = User::find($this->creator_id);
			$Author['author_avatar'] = UtilsHelper::getImage($user->avatar, 'img/dfimg.png');
			$Author['author_id'] = $user->id;
			$Author['author_name'] = $user->realname;			
		}
		return $Author;
	}


	public static function storeArticle($data,$id=null)
	{
		if($id){
			$article = Article::find($id);
			$article_info = ArticleInfo::find($id);
		}
        else{
        	$article = new Article();
        	$article_info = new ArticleInfo();
        }
		$article->class   = $data["class"];
		$article->law_cat   = $data["law_cat"];
		$article->title   = $data["title"];
		$article->keys   = $data["keys"];
		$article->info   = $data["info"];
		$article->creator_id   = Auth::user()->id;
		$article->last_ip   = Request::getClientIp();
		$article->down_group   = $data["down_group"];
        // $article->content = $data["content"];
        if (!isset($data['from_admin'])) {
            $article->from_admin = false;    
        } else {
            $article->from_admin = $data["from_admin"];
        }

        if ($article->from_admin) {
            $article->status   = self::STATUS_APPROVED;
            $article->visibility = self::VISIBILITY_ALL;
        } else {
            $article->status   = $data['status'];
            $article->visibility = $data["visibility"];
        } 
        // 查找上传的文件
        $attachment = null;
		if(isset($data['file_path'])) {
		    $article->file_path = $data['file_path'];
            $attachment = FileAttachment::findAttachmentByFilePath($data['file_path']);
		}
		if(isset($data['img'])) $article->img = $data['img'];
		if(!$id){
        	$article->hits = 0;
        	$article->comments = 0;
        	$article->likes = 0;
        	$article->downs = 0;
		}
        
		$article_info->content = $data['content'];
        DB::transaction(function() use($article, $article_info, $data, $attachment){
            $article->save();
			$article_info->id = $article->id;
			$article_info->created_at = $article->created_at;
			$article_info->updated_at = $article->updated_at;			
            $article_info->save();
            // 绑定上传的文件
            if ($attachment) {
                FileAttachment::bindAttachmentWithItem($attachment->id, $article->id, FileAttachment::ITEM_TYPE_ARTICLE);
            }
        });

        return $article;
	
	}

	public static function updateArticle($id, $data)
	{
        $article = Article::find($id);
		if( ! $article)
		{
			return false;
		}

		$article->class   = $data["class"];
		$article->law_cat   = $data["law_cat"];
		$article->title   = $data["title"];
//		$article->keys   = $data["keys"];
		$article->info   = $data["info"];
		$article->down_group   = $data["down_group"];
        // $article->content = $data["content"];
//        $article->from_admin = $data["from_admin"]; 
		$article->last_ip   = Request::getClientIp();
		if(isset($data['file_path'])) $article->file_path = $data['file_path'];
		if(isset($data['img'])) $article->img = $data['img'];

		$article_info = ArticleInfo::find($id);
        if (!$article_info) {
            $article_info = new ArticleInfo();
            $article_info->id = $id;
        }

        $article_info->content = $data['content'];
        
        // 查找和绑定上传的文件
        $attachment = null;
        if(isset($data['file_path'])) {
            $attachment = FileAttachment::findAttachmentByFilePath($data['file_path']);
        }
        
        DB::transaction(function() use($article, $article_info, $attachment){
            $article->save();
            $article_info->save();
            if ($attachment) {
                FileAttachment::bindAttachmentWithItem($attachment->id, $article->id, FileAttachment::ITEM_TYPE_ARTICLE);
            }
        });
        return $article;
	
	}

    public static function validateId($input){
        $querycondition = ['id'=>$input["id"],'creator_id'=>$input["creator_id"],'from_admin'=>$input["from_admin"]];
        $bo=Article::where($$querycondition);
        if($bo){
            return false;
        }else{
            return array('messages'=>'id错误');
        }


    }

	public static function getArticleClassList($first_option = NULL, $keys)
	{
		$article_class_model = App::make('ArticleClass');
		$query = $article_class_model->where('class_group', $keys);
		$query->orderBy('orders', 'ASC');
		$article_class_datas = $query->get();
		$article_class_list = array();
		if($first_option)
		{
			$article_class_list[] = $first_option;
		}
		foreach($article_class_datas AS $article_class)
		{
				$article_class_list[$article_class->id] = $article_class->name;
		}
		return $article_class_list;
	}

    public function scopeOfSearch($query, $search){

        if ($search)
        {
            $query = $query->where('title', 'LIKE', "%$search%");
        }

        return $query;
    }

    public function scopeOfClass($query, $class){

        if ($class)
        {
            $query = $query->where('class', '=', $class);
        }

        return $query;
    }

    public function scopeOfLawCat($query, $law_cat){

        if ($law_cat)
        {
            $query = $query->where('law_cat', '=', $law_cat);
        }

        return $query;
    }

    public static function getArticles(
        $class, 
        $search, 
        $law_cat, 
        $offset, 
        $limit, 
        $order_by = 'created_at', 
    	$visibility = null,
        $days = null, 
        $status = self::STATUS_APPROVED, 
        $from_admin = 1, 
        $creator_id = null
    )
    {
        $query = Article::leftJoin('user','user.id', '=', 'articles.creator_id')
            ->select(
                'articles.id',
                'articles.title',
                'articles.class',
                'articles.img',
                'articles.law_cat',
                'articles.title',
                'articles.info',
                'articles.hits',
                'articles.downs',
                'articles.comments',
            	'articles.file_path',
                'articles.likes',
                'articles.creator_id',
                'articles.created_at',
                'articles.collects_count',
                'articles.visibility',
            	'articles.from_admin',
            	'articles.creator_id',
                'user.avatar',
                'user.realname',
                'user.follows_count'
            );
        
        if (is_array($class)) {
            $query = $query->whereIn('class', $class);
        } else {
            $query = $query->where('class', '=', $class);
        }

		$query = $query->where('articles.status', '=', $status);

        if ($from_admin) {
            $query = $query->where('from_admin', $from_admin);
        }

        if ($creator_id) {
			$query = $query->where('creator_id', '=', $creator_id);
        }

        if ($search) {
			$query = $query->where('title', 'like', '%'.$search.'%');
        }
        
        if ($law_cat) {
			$query = $query->where('law_cat', '=', $law_cat);
        }
        
        if ($days) {
			$query = $query->where('articles.created_at', '>=', Carbon::now()->subDays($days)->toDateTimeString());
        }

        if($visibility!=null){
			$query = $query->where('visibility', '=', $visibility);
        }

		if($order_by == 'like'){
			$query = $query->orderBy('articles.likes', 'DESC');
		}elseif($order_by == 'downs'){
			$query = $query->orderBy('articles.downs', 'DESC');
		}elseif($order_by == 'views'){
			$query = $query->orderBy('articles.hits', 'DESC');
		}else{
			$query = $query->orderBy('articles.created_at', 'DESC');
		}
        return $query->take($limit)->skip($offset)->get();
    }
    
    /**
     * 最新的律师发布的新闻
     */
    public static function getLatestArticleByLawyer()
    {
    	$article = Article::leftJoin('user','user.id', '=', 'articles.creator_id')
			->select(
			        'user.avatar as creator_avatar',
			        'user.realname as creator_realname',
					'articles.id',
					'articles.title',
					'articles.class',
					'articles.hits',
					'articles.comments',
					'articles.likes',
					'articles.creator_id',
					'articles.created_at'
				)
			->where('user.status', User::STATUS_VERIFIED_LAWYER)
            ->where('articles.status', Article::STATUS_APPROVED)
            ->orderBy('articles.created_at', 'DESC')
    	    ->first();
    	if ($article) {
    	    $article['creator_avatar'] = UtilsHelper::getImage($article['creator_avatar'], 'img/dfimg.png');
            $article['is_following'] = Follow::isFollowing($article['creator_id']);
    	}
    	return $article;
    }
    
    public static function getAllArticles(
    		$offset,
    		$limit,
    		$order_by = 'created_at',
    		$visibility = 0,
    		$status = Article::STATUS_APPROVED,
    		$from_admin = 0
    	)
    {
    	$query = Article::leftJoin('user','user.id', '=', 'articles.creator_id')
			->select(
					'articles.id',
					'articles.title',
					'articles.class',
					'articles.img',
					'articles.law_cat',
					'articles.info',
					'articles.hits',
					'articles.comments',
					'articles.likes',
					'articles.creator_id',
					'articles.created_at',
					'articles.collects_count',
					'articles.visibility',
					'user.avatar',
					'user.realname',
					'user.follows_count'	
				)
			->where('articles.status',$status)
            ->take($limit)
            ->skip($offset)
            ->orderBy('articles.'.$order_by, 'DESC');

        if($visibility!=null){
            $query->where('visibility', '=', $visibility);
        }
        $query->where(array('articles.status' => $status, 'from_admin' => $from_admin));
        return $query->get();
    }
    
    public function getLawCat(){
    	$lawCat = ArticleClass::find($this->law_cat);
    	if($lawCat){
    		return $lawCat->name;
    	}
    	else return "其他";
    }
    
    public function getClass(){
    	$class = ArticleClass::find($this->class);
    	return $class->name;
    }
    
    public function isCollect(){
    	$is_collect = Collect::where('item_id', $this->id)->where('collect_type', Collect::TYPE_ARTICLE)->where('creator_id', Auth::user()->id)->first();
    	return (bool)$is_collect;
    }
    
    public function isLiked(){
        $is_liked = Like::where('item_id', $this->id)->where('like_type', Like::TYPE_ARTICLE)->where('creator_id', Auth::user()->id)->first();
        return (bool)$is_liked;
    }

    /**
     * @TODO data integrity problem while saving an article
     */
    public function getContent() {
        $info = ArticleInfo::find($this->id);
        if ($info) {
            return $info->content;
        } else {
            return "";
        }
    }
}
